package com.roxas.nfc;

import java.nio.charset.Charset;
import java.util.List;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.IntentFilter.MalformedMimeTypeException;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.NfcAdapter.OnNdefPushCompleteCallback;
import android.nfc.NfcEvent;
import android.nfc.Tag;
import android.nfc.tech.Ndef;
import android.nfc.tech.NfcF;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.telephony.SmsManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.URLUtil;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.roxas.nfc.test.WifiUtil;

public class MainActivity extends Activity {

	private static final int MSG_ON_NDEFPUSH_COMPLETE = 1;

	private static boolean writeMode;
	private static String content;
	private static String phoneNumber;
	private Context context;
	private NfcAdapter nfcAdapter;
	private TextView waitWriteTxt;
	private Button writeBtn;
	private TextView pushWebTxt;
	private EditText pushWebET;
	private Button pushWebBtn;
	private Button connectWifi;

	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MSG_ON_NDEFPUSH_COMPLETE:
				enableForegroundDispatch();
				pushWebTxt.setVisibility(View.GONE);
				pushWebBtn.setEnabled(true);
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		context = this;
		initViews();
	}

	private void initViews() {
		nfcAdapter = NfcAdapter.getDefaultAdapter(context);

		final EditText contentET = (EditText) findViewById(R.id.editText1);
		final EditText phoneNumberET = (EditText) findViewById(R.id.editText2);
		waitWriteTxt = (TextView) findViewById(R.id.textView1);
		writeBtn = (Button) findViewById(R.id.button1);
		if (writeMode) {
			waitWriteTxt.setVisibility(View.VISIBLE);
			writeBtn.setEnabled(false);
		}
		writeBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				content = contentET.getText().toString();
				phoneNumber = phoneNumberET.getText().toString();
				if (TextUtils.isEmpty(content) || TextUtils.isEmpty(phoneNumber)) {
					Toast.makeText(context, "内容不能为空!", Toast.LENGTH_SHORT).show();
					return;
				}
				v.setEnabled(false);
				writeMode = true;
				waitWriteTxt.setVisibility(View.VISIBLE);
			}
		});

		pushWebTxt = (TextView) findViewById(R.id.textView2);
		pushWebET = (EditText) findViewById(R.id.editText3);
		pushWebET.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {

			}

			@Override
			public void afterTextChanged(Editable s) {
				String content = s.toString();
				if (!content.contains("http://")) {
					pushWebET.setText("http://" + content);
					pushWebET.setSelection(("http://" + content).length());
				}

			}
		});
		pushWebBtn = (Button) findViewById(R.id.button2);
		pushWebBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				String url = pushWebET.getText().toString();
				if (!URLUtil.isNetworkUrl(url)) {
					Toast.makeText(context, "输入网址无效,请重新输入!", Toast.LENGTH_SHORT).show();
					return;
				}
				NdefRecord ndefRecord = NdefRecord.createUri(url);
				NdefRecord[] ndefRecords = new NdefRecord[] { ndefRecord };
				NdefMessage mMessage = new NdefMessage(ndefRecords);

				if (nfcAdapter != null) {
					nfcAdapter.disableForegroundDispatch(MainActivity.this);
					nfcAdapter.setNdefPushMessage(mMessage, MainActivity.this);
					pushWebTxt.setVisibility(View.VISIBLE);
					v.setEnabled(false);
				}
			}
		});
		nfcAdapter.setOnNdefPushCompleteCallback(new OnNdefPushCompleteCallback() {

			@Override
			public void onNdefPushComplete(NfcEvent event) {
				handler.obtainMessage(MSG_ON_NDEFPUSH_COMPLETE).sendToTarget();
			}
		}, this);

		connectWifi = (Button) findViewById(R.id.button3);
		connectWifi.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				WifiUtil wifiUtil = new WifiUtil(context);
				wifiUtil.openWifi();
				wifiUtil.addNetwork(wifiUtil.CreateWifiInfo("CC", "IAMCCMATE", 3));
			}
		});
	}

	@Override
	protected void onResume() {
		super.onResume();
		enableForegroundDispatch();
		Tag tag = getIntent().getParcelableExtra(NfcAdapter.EXTRA_TAG);
		if (tag == null) {
			return;
		}
		if (writeMode) {
			writeTag(getIntent());
		} else {
			sendSms(getIntent());
		}
	}

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		if (writeMode) {
			writeTag(intent);
		} else {
			sendSms(intent);
		}
	}

	private void sendSms(Intent intent) {
		Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
		if (rawMsgs == null || rawMsgs.length == 0) {
			Toast.makeText(context, "此标签无数据!", Toast.LENGTH_LONG).show();
			return;
		}
		NdefMessage msg = (NdefMessage) rawMsgs[0];
		if (msg == null) {
			Toast.makeText(context, "此标签无数据!", Toast.LENGTH_LONG).show();
			return;
		}
		String localContent = "";
		String localPhoneNumber = "";
		for (int i = 0; i < msg.getRecords().length; i++) {
			switch (i) {
			case 0:
				localContent = new String(msg.getRecords()[i].getPayload());
				break;
			case 1:
				localPhoneNumber = new String(msg.getRecords()[i].getPayload());
				break;
			}
		}

		if (TextUtils.isEmpty(localContent) || TextUtils.isEmpty(localPhoneNumber)) {
			Toast.makeText(context, "此标签无数据!", Toast.LENGTH_LONG).show();
			return;
		}
		SmsManager smsManager = SmsManager.getDefault();
		if (localContent.length() > 70) {
			List<String> contents = smsManager.divideMessage(localContent);
			for (String sms : contents) {
				smsManager.sendTextMessage(localPhoneNumber, null, sms, null, null);
			}
		} else {
			smsManager.sendTextMessage(localPhoneNumber, null, localContent, null, null);
		}
		Toast.makeText(this, "短信发送成功！", Toast.LENGTH_LONG).show();
		finish();
	}

	private void writeTag(Intent intent) {
		Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
		if (tag == null) {
			return;
		}
		Ndef ndef = Ndef.get(tag);
		NdefRecord recordContent = new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_TEXT, new byte[0], content.getBytes(Charset.forName("UTF-8")));
		NdefRecord recordPhoneNumber = new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_TEXT, new byte[0], phoneNumber.getBytes(Charset.forName("UTF-8")));
		try {
			NdefRecord[] records = { recordContent, recordPhoneNumber };
			NdefMessage message = new NdefMessage(records);
			ndef.connect();
			ndef.writeNdefMessage(message);
			Toast.makeText(this, "写入成功!", Toast.LENGTH_SHORT).show();
		} catch (Exception e) {
			Toast.makeText(this, "写入失败!", Toast.LENGTH_SHORT).show();
			e.printStackTrace();
		} finally {
			writeBtn.setEnabled(true);
			waitWriteTxt.setVisibility(View.GONE);
			writeMode = false;
		}
	}

	private void enableForegroundDispatch() {
		PendingIntent mPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
		IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
		ndef.addCategory(Intent.CATEGORY_DEFAULT);
		try {
			ndef.addDataType("*/*");
		} catch (MalformedMimeTypeException e) {
			throw new RuntimeException("fail", e);
		}
		IntentFilter[] mFilters = new IntentFilter[] { ndef, };
		String[][] mTechLists = new String[][] { new String[] { NfcF.class.getName() } };
		nfcAdapter.enableForegroundDispatch(this, mPendingIntent, mFilters, mTechLists);
	}

	@Override
	protected void onPause() {
		super.onPause();
		nfcAdapter.disableForegroundDispatch(this);
	}
}
